import Vue from "vue";
import { isEmpty, get } from "lodash/core";
import qs from "query-string";
import Config from "@/config/index";

/**
 *
 *
 * @export
 * @param {Number} value
 * @returns
 */
export function returnFloat(value) {
  // var value=Math.round(parseFloat(value)*100)/100;
  if (!checkStr(value, "number")) {
    return value;
  }
  let xsd = value.toString().split(".");
  let new_value;
  if (xsd.length == 1) {
    value = value.toString() + ".00";
    new_value = value;
  }
  if (xsd.length > 1) {
    if (xsd[1].length < 2) {
      value = value.toString() + "0";
    } else {
      value = xsd[0] + "." + xsd[1].substr(0, 2);
    }
    new_value = value;
  }
  // console.log(new_value, parseFloat(new_value));
  return new_value;
}
/**
 * 防止store参数重名
 *
 * @export
 * @param {String} prefix
 * @returns
 */
export function makeConstCreator(prefix) {
  const constantList = [];
  return constant => {
    const s = `${prefix}/${constant}`;
    if (constantList.indexOf(s) !== -1) {
      throw new Error(`Duplicated store constants:${s}`);
    } else {
      constantList.push(s);
      return s;
    }
  };
}

/**
 * 获取模块路径
 *
 * @export
 * @param {Function} importter
 * @returns
 */
export function getComponentCreator(importter) {
  return (...path) =>
    importter().then(component => {
      let result = component;
      if (!isEmpty(path)) {
        result = get(component, `default.${path.join(".")}`);
      }
      return result;
    });
}

/**
 * 修改state
 *
 * @export
 * @param {Object} state
 * @param {Object} payload
 */
export function assignStoreState(state, payload) {
  Object.keys(payload).forEach(key => {
    if (typeof payload[key] !== "undefined") {
      if (state[key] !== payload[key]) {
        Vue.set(state, key, payload[key]);
      }
    }
  });
}

const DEFAULT_DEALY_DURATION = 1000;
/**
 * 手动延迟
 *
 * @export
 * @param {Number} [duration=DEFAULT_DEALY_DURATION]
 * @returns
 */
export function delayPromise(duration = DEFAULT_DEALY_DURATION) {
  return new Promise(resolve => {
    setTimeout(resolve, duration);
  });
}
/**
 *
 *
 * @export
 * @param {Number} n
 * @returns
 */
export function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}
/**
 * 框架内跳转
 *
 * @export
 * @param {Object} {
 *   base = '/unileak/index.html#/',
 *   target,
 *   params = {},
 *   title,
 * }
 */
export function innerOpen({
  base = "/unileak/index.html#/",
  target,
  params = {},
  title
}) {
  // 开发调试
  if (!Config.production) {
    let url = window.location.href;
    let url_arr = url.split("#");
    let newurl = `${url_arr[0]}#${target}?${qs.stringify(params)}`;
    window.open(newurl, title);
    return;
  }
  // 在大框架下起作用
  const sign = "#!";
  const url = `${base}${target}?${qs.stringify(params)}${
    title ? `&_title=${encodeURIComponent(title)}` : ""
  }`;

  try {
    window.top.location.hash = `${sign}${url}`;
  } catch (e) {
    console.error(`innerOpen errer: ${e}`);
    try {
      /* eslint-disable */
      window.ShowDialog({
        Title: title,
        Url: `${base}${target}?${qs.stringify(params)}`,
        Height: $(window).height() - 80,
        Width: $(window).width() - 80,
      });
      /* eslint-enable */
    } catch (error) {
      console.error(`window.ShowDialog error: ${error}`);
      window.location.href = url;
    }
  }
}
/*类型验证*/
/**
 *
 *
 * @export
 * @param {*} str
 * @param {String} type
 * @returns
 */
export function checkStr(str, type) {
  switch (type) {
    case "phone":
      //手机号码
      return /^1[3|4|5|7|8][0-9]{9}$/.test(str);
    case "tel":
      //座机
      return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str);
    case "card":
      //身份证
      return /^\d{15}|\d{18}$/.test(str);
    case "pwd":
      //密码以字母开头，长度在6~18之间，只能包含字母、数字和下划线
      return /^[a-zA-Z]\w{5,17}$/.test(str);
    case "postal":
      //邮政编码
      return /[1-9]\d{5}(?!\d)/.test(str);
    case "QQ":
      //QQ号
      return /^[1-9][0-9]{4,9}$/.test(str);
    case "email":
      //邮箱
      return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str);
    case "money":
      //金额(小数点2位)
      return /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(
        str
      );
    case "URL":
      //网址
      return /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(
        str
      );
    case "IP":
      //IP
      return /((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))/.test(
        str
      );
    case "date":
      //日期时间
      return (
        /^(\d{4})\-(\d{2})\-(\d{2}) (\d{2})(?:\:\d{2}|:(\d{2}):(\d{2}))$/.test(
          str
        ) || /^(\d{4})\-(\d{2})\-(\d{2})$/.test(str)
      );
    /* case "number":
        //数字
        return /^[0-9]*$/.test(str); */
    case "number":
      //数字
      return /^(\+|\-)?(0|([1-9]\d*?))(\.\d+?)?$/.test(str);
    case "integers":
      //数字
      return /^-?[1-9]\d*$/.test(str);
    case "integer":
      //非负整数
      return /^(0|[1-9]\d*)$/.test(str);
    case "integer5":
      //非负整数1-5
      return /^[0-5]$/.test(str);
    case "english":
      //英文
      return /^[a-zA-Z]+$/.test(str);
    case "chinese":
      //中文
      return /^[\u4E00-\u9FA5]+$/.test(str);
    case "lower":
      //小写
      return /^[a-z]+$/.test(str);
    case "upper":
      //大写
      return /^[A-Z]+$/.test(str);
    case "HTML":
      //HTML标记
      return /<("[^"]*"|'[^']*'|[^'">])*>/.test(str);
    default:
      return true;
  }
}
